package cn.fl.mcr.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrWriteOffConfirmDetailService;
import cn.fl.mcr.util.ExcelReportUtil;
import cn.fl.mcr.vo.McrBillMVO;
import cn.fl.mcr.vo.McrWriteOffConfirmDetailDVO;
import cn.fl.system.constant.SysLogConstant;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrBillMQC;
import cn.lionbridgecapital.loan.model.condition.McrInformTransferQC;
import cn.lionbridgecapital.loan.model.condition.McrWriteOffConfirmDetailQC;
import cn.lionbridgecapital.loan.model.dto.McrInformTransferDTO;
import cn.lionbridgecapital.loan.model.dto.McrLoanAccountDTO;
import cn.lionbridgecapital.loan.model.vo.McrWriteOffConfirmDetailVO;

/**
 * @Description: 核销确认明细 控制层
 */
@Controller
@RequestMapping("/mcr/mcrWriteOffConfirmDetail")
public class McrWriteOffConfirmDetailController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(McrWriteOffConfirmDetailController.class);

	/**
	 * McrWriteOffConfirmDetail 服务层BEAN
	 */
	@Autowired
	private IMcrWriteOffConfirmDetailService mcrWriteOffConfirmDetailService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mcr/mcrWriteOffConfirmDetail/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mcr/mcrWriteOffConfirmDetail/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		McrWriteOffConfirmDetailQC qc = new McrWriteOffConfirmDetailQC();
		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = new Pager();//this.mcrWriteOffConfirmDetailService.searchListPage(page);
		List<McrWriteOffConfirmDetailVO> list = (List<McrWriteOffConfirmDetailVO>) pager.getResultList();
		ListPageVO<McrWriteOffConfirmDetailVO> listPage = new ListPageVO<McrWriteOffConfirmDetailVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.mcrWriteOffConfirmDetailService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			McrWriteOffConfirmDetailVO vo = this.mcrWriteOffConfirmDetailService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		McrWriteOffConfirmDetailVO entity = null;
		try {
			entity = new McrWriteOffConfirmDetailVO();
			//TODO ADD PARAM
			Long id = this.mcrWriteOffConfirmDetailService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		McrWriteOffConfirmDetailVO entity = null;
		try {
			entity = new McrWriteOffConfirmDetailVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.mcrWriteOffConfirmDetailService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	/**
	 * 核销款明细页面
	 */
	@RequestMapping(value = "/checkDetails.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView checkDetails(HttpServletRequest request, HttpServletResponse response) {
		String batNo = request.getParameter("batNo");
		ModelAndView view = new ModelAndView("mcr/mcrWriteOffConfirmDetail/checkDetails");
		view.addObject("batNo", batNo);
		BaseLogUtils.info(logger, "checkDetails", "核销款明细页面.[batNo="+batNo+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 
	 * @Title: checkDetailsList   
	 * @Description: 核销款明细列表
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ModelAndView      
	 * @throws
	 */
	@RequestMapping(value = "/checkDetailsList.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object checkDetailsList(HttpServletRequest request, HttpServletResponse response) {
		String batNo = request.getParameter("batNo");
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		McrWriteOffConfirmDetailQC qc = new McrWriteOffConfirmDetailQC();
		qc.setBatNo(batNo);
		page.setCondition(qc);
		//根据批次号查询核销款明细
		Pager pager = this.mcrWriteOffConfirmDetailService.searchListPage(page);
		BaseLogUtils.info(logger, "checkDetailsList", "核销款明细查询返回数据:" + JSONObject.toJSONString(pager), CurrentThreadContext.getCurrentUserName());
		List<McrWriteOffConfirmDetailDVO> list = (List<McrWriteOffConfirmDetailDVO>) pager.getResultList();
		ListPageVO<McrWriteOffConfirmDetailDVO> listPage = new ListPageVO<McrWriteOffConfirmDetailDVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "checkDetailsList", "核销款明细页面查询数据完成. DATA:" + JSONObject.toJSONString(listPage), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	
	
	/**
	 * 
	 * @Title: exportexcel   
	 * @Description: 下载  
	 * @param: @param request
	 * @param: @param response      
	 * @return: void      
	 * @throws
	 */
	@SuppressWarnings(value = "unchecked")
    @RequestMapping(value = "/exportexcel.do", method = {RequestMethod.POST, RequestMethod.GET})
    public void exportexcel(HttpServletRequest request, HttpServletResponse response) {
		String batNos = request.getParameter("batNos");
		BaseLogUtils.info(logger, "exportexcel", "McrWriteOffConfirmDetailController.exportexcel>>batNo:" + batNos, CurrentThreadContext.getCurrentUserName());
		Pager page = new Pager();
		McrWriteOffConfirmDetailQC qc = new McrWriteOffConfirmDetailQC();
		if(StringUtils.isNotEmpty(batNos)){
            String[] split = batNos.split(",");
            List<String> strings = Arrays.asList(split);
            qc.setBatNoList(strings);
        }else {
        	BaseLogUtils.info(logger, "exportexcel", "McrWriteOffConfirmDetailController.exportexcel 导出失败,未选中数据" , CurrentThreadContext.getCurrentUserName());
        	return ;
        }
		page.setEveryPage(2000);
		page.setCondition(qc);
		//根据批次号查询核销款明细
		Pager pager = this.mcrWriteOffConfirmDetailService.searchListPage(page);
		List<McrWriteOffConfirmDetailDVO> confirmDetailList = (List<McrWriteOffConfirmDetailDVO>) pager.getResultList();
		BaseLogUtils.info(logger, "exportexcel", "McrWriteOffConfirmDetailController.exportexcel>>confirmDetailList:" + JSON.toJSONString(confirmDetailList), CurrentThreadContext.getCurrentUserName());
		List<Map<String, Object>> contentMap = Lists.newArrayList();
		if(CollectionUtils.isNotEmpty(confirmDetailList)) {
			for(McrWriteOffConfirmDetailDVO vo:confirmDetailList) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("pactNo", vo.getPactNo());//合同号
				map.put("cstNm", vo.getCstNm());//客户姓名
				Date repayDate = vo.getRepayDate();
				if(null != repayDate) {
					map.put("repayDate", DateUtils.formatDateToString( vo.getRepayDate(), DateUtils.YYYY_MM_DD) );//实收时间
				}else {
					map.put("repayDate","");
				}
				String repayType = vo.getRepayType();//实收类型
				String repayTypeDesc = "";
				if(repayType.equals("1")){
					repayTypeDesc =  "待确认";
				}else if(repayType.equals("2")){
					repayTypeDesc = "合同生成";
				}else if(repayType.equals("3")){
					repayTypeDesc = "放款中";
				}else if(repayType.equals("4")){
					repayTypeDesc = "已放款";
				}else if(repayType.equals("5")){
					repayTypeDesc = "放款失败";
				}else if(repayType.equals("6")){
					repayTypeDesc = "正常结清";
				}else if(repayType.equals("7")){
					repayTypeDesc = "提前结清";
				}else if(repayType.equals("8")){
					repayTypeDesc = "强制结清";
				}else if(repayType.equals("9")) {
					repayTypeDesc = "作废";
				}
				map.put("repayType", repayTypeDesc);
				map.put("perdNo", vo.getPerdNo());//还款期次
				map.put("repayAmt", vo.getRepayAmt());//实收金额(元)
				map.put("repayPrincipal", vo.getRepayPrincipal());//实收本金(元)
				map.put("repayInterest", vo.getRepayInterest());//实收利息(元)
				map.put("repayPenaltyInterest", vo.getRepayPenaltyInterest());//实收罚息(元)
				contentMap.add(map);
			}
		}
		BaseLogUtils.info(logger, "exportexcel", "McrWriteOffConfirmDetailController.exportexcel>>contentMap:"+JSON.toJSONString(contentMap),CurrentThreadContext.getCurrentUserName());
		String[][] headers = {{"合同号","客户姓名","实收时间","实收类型","还款期次","实收金额(元)","实收本金(元)","实收利息(元)","实收罚息(元)"}
		,{"pactNo","cstNm","repayDate","repayType","perdNo","repayAmt","repayPrincipal", "repayInterest", "repayPenaltyInterest"}};
		BaseLogUtils.info(logger, "exportexcel", "McrWriteOffConfirmDetailController.exportexcel开始",CurrentThreadContext.getCurrentUserName());
		ExcelReportUtil.exportExcelReportPage("五矿线下核销明细", headers, contentMap, response, request);
		BaseLogUtils.info(logger, "exportexcel", "McrWriteOffConfirmDetailController.exportexcel完成",CurrentThreadContext.getCurrentUserName());
	}
	
}

